package cn.itsource.pethome.system.dept.service.imp;

import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.system.dept.domain.Department;
import cn.itsource.pethome.system.dept.mapper.DepartmentMapper;
import cn.itsource.pethome.system.dept.service.IDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:R
 * @Date:2022/12/28 19:49
 * Description
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    //构造方法注入
    final DepartmentMapper departmentMapper;
    public DepartmentServiceImpl(DepartmentMapper departmentMapper){
        this.departmentMapper = departmentMapper;
    }

    @Override
    @Transactional
    public void add(Department department) {
        //拼接dirpath
        departmentMapper.add(department);
        buildDirPath(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        buildDirPath(department);
    }

    //构建dirpath
    private void buildDirPath(Department department) {
        Long id = department.getId();
        Long parentId = department.getParent_id();
        if(parentId == null){  //自己就是顶级部门
            department.setDirPath("/"+id);
        }else { //自己不是顶级部门，就获取父级部门的dirpath，填充到自己的dirpath的前面
            String dirPath = departmentMapper.findOne(parentId).getDirPath();
            String[] split = dirPath.split("/");
            for (String s : split) {
                if (s.equals(String.valueOf(id))){
                    throw new RuntimeException("不能将自己添加到自己的子级部门");
                }
            }
            department.setDirPath(dirPath+"/"+id);
        }
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //有子级部门就不能删除
        Long all = departmentMapper.findAllByParentId(id);
        if (all == 0){  // 没有子级部门
            departmentMapper.delete(id);
        }else {
            throw new RuntimeException("当前部门存在子部门，您不能直接删除");
        }
    }

    //获取部门树
    @Override
    public List<Department> deptTree() {
        List<Department> all = departmentMapper.findAll();
        List<Department> firstTree = new ArrayList<>();
        for (Department department : all) {
            //顶级部门
            if (department.getParent_id() == null){
                firstTree.add(department);
            }else { //非顶级部门的，就去找父级部门，然后把自己放入父级部门的children中
                for (Department department1 : all) {
                    if (department.getParent_id() == department1.getId()){
                        department1.getChildren().add(department);
                    }
                }
            }
        }
        return firstTree;
    }
}
